#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::updateFrame);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::updateFrame()
{
    cv::Mat image;
    camera >> image;
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    QPixmap pic = QPixmap::fromImage(QImage(image.data, image.cols, image.rows, (int)image.step, QImage::Format_RGB888));
    ui->camLabel->setPixmap(pic.scaled(ui->camLabel->size(), Qt::KeepAspectRatio));
}

void Widget::on_openButton_clicked(bool checked)
{
    if (checked)
    {
        //camera.open("http://admin:admin@192.168.137.110:8081/video");
        camera.open(0, cv::CAP_V4L2);
        int fps = camera.get(cv::CAP_PROP_FPS);
        timer->start(1000/fps);
        ui->openButton->setText("Close");
    }
    else
    {
        timer->stop();
        camera.release();
        ui->openButton->setText("Open");
    }
}

